var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();

let rewardedVideoAd = null;//广告组件-激励性广告


Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc: 1,
    util: util,

    showAuthView: false,

    userinfo: {},
    cuid: 0,
    token: '',
    openid: '',

    guiGoodsInfo: '',

    totalPrice: 0,
    colorSet: '',

    content_w: 318,
    item_min_w: 60,
    item_max_w: 120,
    item_min_h: 80,
    item_max_h: 160,

    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 600,
    startTime: 0,
    swiper_w: 320,
    swiper_h: 160,
    swiperImgUrls: '',

    showBuyView: false,
    selBoxData: '',

    screen_w: 320,

    cang5_goodview_w: 90,
    cang5_goodimg_w: 70,
    cang5_1_x: 0,
    cang5_1_y: 0,
    cang5_2_x: 0,
    cang5_2_y: 0,
    cang5_3_x: 0,
    cang5_3_y: 0,
    cang5_4_x: 0,
    cang5_4_y: 0,
    cang5_5_x: 0,
    cang5_5_y: 0,
    cang5_6_x: 0,
    cang5_6_y: 0,
  },

  isOnLoad: false,
  wxAuthFail: true,
  guiId: '',
  guiIsOnline: true,
  orgInfo: '',

  connectWIFI: false,

  cang5_margin: 15,

  adLoadSuccess: false,

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.isOnLoad = true;

    this.guiId = options.guiid ? options.guiid : '';
    //是不是连接Wi-Fi二维码
    this.connectWIFI = options.wifi ? (options.wifi == 'true') : false;
    //记录扫码事件
    this.recordScan();

    var tc = app.get_tc();
    var that = this;

    wx.getSystemInfo({
      success: function (res) {
        var min_w = (res.windowWidth - 30) / 5;
        var max_w = (res.windowWidth - 20) / 3;
        var min_h = min_w * 1.25;


        let yuanxin = (res.windowWidth - 30) / 2;
        let goodImgW = (res.windowWidth - 50) / 3;
        let banjing = yuanxin - goodImgW / 2;
        let zhengxianzhi36 = 0.5878;
        let zhengxianzhi54 = 0.809;
        let zhengxianzhi18 = 0.309;
        let zhengxianzhi72 = 0.9511;

        that.setData({
          screen_w: res.windowWidth,
          content_w: res.windowWidth,
          item_min_w: min_w,
          item_max_w: max_w,
          item_min_h: min_w + 25,
          item_max_h: max_w + 25,
          swiper_w: res.windowWidth,
          swiper_h: res.windowWidth / 3,

          cang5_goodview_w: goodImgW,
          cang5_goodimg_w: goodImgW - 20,
          cang5_1_x: yuanxin - (banjing * zhengxianzhi36) - goodImgW / 2,
          cang5_1_y: yuanxin - (banjing * zhengxianzhi54) - goodImgW / 2,
          cang5_2_x: yuanxin + (banjing * zhengxianzhi36) - goodImgW / 2,
          cang5_2_y: yuanxin - (banjing * zhengxianzhi54) - goodImgW / 2,
          cang5_3_x: yuanxin + (banjing * zhengxianzhi72) - goodImgW / 2,
          cang5_3_y: yuanxin + (banjing * zhengxianzhi18) - goodImgW / 2,
          cang5_4_x: yuanxin - goodImgW / 2,
          cang5_4_y: yuanxin + (banjing - goodImgW / 2),
          cang5_5_x: yuanxin - (banjing * zhengxianzhi72) - goodImgW / 2,
          cang5_5_y: yuanxin + (banjing * zhengxianzhi18) - goodImgW / 2,
          cang5_6_x: yuanxin - goodImgW / 2,
          cang5_6_y: yuanxin - goodImgW / 2 + 8,
        })
      },
    })

    app.GetUserInfo(util.orgid, function (res) {
      console.log("绑定小程序信息：", res);
      that.orgInfo = res;
      that.showAuthView(false, false);
    });
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('gui/gui', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor
      });
    });
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    if (this.guiId) {
      this.getGuiInfo();
    } else {
      wx.showModal({
        title: '提示',
        content: '未能获取售货机ID，请检查小程序码是否正确',
        showCancel: false
      })
    }
    this.loadSwiperImage();

    if (this.connectWIFI) {
      wx.navigateTo({
        url: '/pages/wifi-connect/wifi-connect',
      })
    }



    console.log("准备初始化广告组件");
    if (wx.createRewardedVideoAd) {
      console.log("存在广告组件，去初始化");
      rewardedVideoAd = wx.createRewardedVideoAd({ adUnitId: 'adunit-b78b770c457617af' })
      rewardedVideoAd.onLoad(() => {
        that.adLoadSuccess = true;
        console.log('onLoad 广告初始化成功')
      })
      rewardedVideoAd.onError((err) => {
        console.log('onError 广告初始化失败')
        console.log('onError event emit', err)
      })
      rewardedVideoAd.onClose((res) => {
        console.log('onClose 用户广告关闭', res)
        // 用户点击了【关闭广告】按钮
        if (res && res.isEnded) {
          // 正常播放结束，可以充电了
          that.buyChongdian(that.selTarget);
        } else {
          // 播放中途退出，不下发游戏奖励
          wx.showModal({
            title: "提示",
            content: "未观看完视频，看完才可以充电哦",
            showCancel: false
          })
        }
      })

    }


  },


  userCancelAuth: function () { //用户取消授权
    this.hiddenAuthView();
    wx.navigateBack({
      delta: 1
    })
  },
  showAuthView: function (showCancel, reAuth) {
    var that = this;
    wx.getSetting({
      success: (res) => {
        console.log("已授权列表：", res);
        var authStatus_userInfo = res.authSetting["scope.userInfo"];
        if (authStatus_userInfo) {
          that.getLoginUserInfo();
        } else {
          var authToastOb = {};
          authToastOb.showCancel = showCancel;
          authToastOb.msg = that.orgInfo.uname + " 需要您的授权"
          that.setData({
            showAuthView: true,
            authToastData: authToastOb
          })
        }
      }
    });
  },
  hiddenAuthView: function () {
    this.setData({
      showAuthView: false
    })
  },
  loginUserInfo: function (res) {
    if (res.detail.encryptedData) { //如果包含有这个字段，说明用户授权了
      this.getLoginUserInfo();
    }
  },

  getLoginUserInfo: function () {
    var that = this;
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    });
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      if (res && res != -1) {
        that.wxAuthFail = false;
        //更新数据
        that.setData({
          cuid: res.uid,
          openid: res.wxsmall_openid,
          token: res.token
        })
        //更新扫码事件，记录扫码者
        that.updateRecord();
        util.api({
          data: {
            "uid": res.uid,
            "publickey": util.publiccode,
            "ac": "userinfo"
          },
          success: function (responseData) {
            console.log("用户信息：", responseData.data);
            that.setData({
              userInfo: responseData.data
            });
            if (that.isOnLoad && that.data.userinfo.verified == '1' && that.data.userinfo.usercata == '81') {
              that.isOnLoad = false;
              that.goManageGuiPage();
            }
          }
        });
      } else {
        that.wxAuthFail = true;
      }
      wx.hideLoading();
    }, '');
  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({
        url: path
      });
    }
  },

  liuyanInput: function (e) {
    console.log("留言：" + e.detail.value);
    this.setData({
      liuyan: e.detail.value
    });
  },

  //获取柜子的商品信息
  getGuiInfo: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getguiinfo",
        "guiid": that.guiId
      },
      success: function (responseData) {
        console.log("柜子的商品信息：", responseData);
        var guiInfo = responseData.data;
        var noticeText = '';
        if (!guiInfo.isalive) {
          noticeText = '此自动售货机连接异常，请勿购买';
          guiInfo.err_msg = noticeText;
        }

        that.guiIsOnline = true;
        var titlename = guiInfo.title ? guiInfo.title : '自助售货机';
        let start = guiInfo.guiid.length - 4;
        guiInfo.showguiid = "ID: ******" + guiInfo.guiid.substr(start, 4)
        wx.setNavigationBarTitle({
          title: titlename,
        })
        that.setData({
          guiGoodsInfo: guiInfo
        });

        if (!guiInfo.isalive) {
          that.guiIsOnline = false;
          wx.showModal({
            title: '温馨提示',
            content: noticeText,
            showCancel: false
          });

        }
      }
    });
  },

  selBoxId: 0,
  selBosIsCongdian: 0,
  hideBuyView: function () {
    this.selBoxId = 0;
    this.setData({
      selBoxData: '',
      showBuyView: false
    });
  },

  selBoxAction: function (e) {
    if (this.wxAuthFail) {
      this.showAuthView(false, false);
    } else {
      if (!this.guiIsOnline) {
        wx.showModal({
          title: '温馨提示',
          content: '此自动售货机连接异常，请勿购买',
          showCancel: false
        });
        return;
      }
      var selBoxData = e.currentTarget.dataset.boxdata;
      this.selBoxId = e.currentTarget.dataset.boxid;
      if (selBoxData.isfull != '1') {
        let that = this;
        wx.showModal({
          title: '温馨提示',
          content: '系统显示此商品已售，如舱门未弹开，请点击“开门”，如需要更多商品请联系服务人员',
          confirmText: "开门",
          success: function (res) {
            if (res.confirm) {
              that.openGuiBox(that.selBoxId);
            }
          }
        });
        return;
      }

      this.setData({
        selBoxData: selBoxData,
        showBuyView: true
      });
    }
  },

  chondianAction: function (e) {
    var that = this;
    if (this.wxAuthFail) {
      this.showAuthView(false, false);
    } else {
      if (!this.guiIsOnline) {
        wx.showModal({
          title: '温馨提示',
          content: '此自动售货机连接异常，请勿购买',
          showCancel: false
        });
        return;
      }

      let cdtime = wx.getStorageSync('cdtime');
      if (!cdtime) {
        console.log("没有缓存");
        //显示广告
        that.selTarget = e;
        rewardedVideoAd.show()
          .catch(() => {
            rewardedVideoAd.load()
              .then(() => rewardedVideoAd.show())
              .catch(err => {
                wx.showToast({
                  title: '视频正在赶来中',
                })
              })
          })


      } else {
        let curtime = (new Date().getTime()) / 1000;
        if (curtime - cdtime < 600) {//十分钟内
          let orderId = wx.getStorageSync('orderid');
          let boxId = wx.getStorageSync('boxId');
          that.openchongdian(orderId, boxId);
        } else {
          wx.setStorageSync('cdtime', '');
          wx.setStorageSync('orderid', '');
          wx.setStorageSync('boxId', '');
          that.selTarget = e;
          rewardedVideoAd.show()
            .catch(() => {
              rewardedVideoAd.load()
                .then(() => rewardedVideoAd.show())
                .catch(err => {
                  wx.showToast({
                    title: '视频正在赶来中',
                  })
                })
            })

        }
      }


    }

  },

  selTarget: '',

  buyChongdian: function (e) {
    var that = this;
    var goodsItem6 = this.data.guiGoodsInfo.box6;
    var goodsItem7 = this.data.guiGoodsInfo.box7;
    var price6 = parseInt(goodsItem6.sellprice) / 100;
    var price7 = parseInt(goodsItem7.sellprice) / 100;
    this.selBosIsCongdian = e.currentTarget.dataset.congdian ? e.currentTarget.dataset.congdian : 0;
    this.selTarget = '',
      wx.showModal({
        title: "温馨提示",
        content: "充电: 2小时--" + price6 + "元； 12小时--" + price7 + "元。",
        confirmText: "8小时",
        cancelText: "2小时",
        success: function (res) {
          if (res.confirm) {
            that.selBoxId = 7;
          } else {
            that.selBoxId = 6;
          }

          that.paygoodsCard("");
        }
      })
  },

  //购买物品
  paygoodsCard: function (e) {
    var that = this;
    var boxId = that.selBoxId;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'wxsmallpaycarts' + that.data.token);
    var cartinfoArr = [];
    var pin = 0;
    var goodsItem = this.data.guiGoodsInfo["box" + boxId];
    var price = parseInt(goodsItem.sellprice);
    var g_info = {};
    g_info.goods_id = goodsItem.id;
    g_info.goods_name = goodsItem.topictitle;
    g_info.guige = '';
    g_info.count = 1;
    g_info.yunfei = 0;
    g_info.coin = price;
    g_info.linkcode = '';
    cartinfoArr = cartinfoArr.concat(g_info);

    let start = that.guiId.length - 4;
    let subJect = '房号:' + this.data.guiGoodsInfo.roomid + ' 机柜:' + that.guiId.substr(start, 4);
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),
      'uid': that.data.cuid,
      'type': 'goods',
      'total_fee': parseFloat(price / 100.0).toFixed(2),
      'allcoin': price,
      'consignee': "匿名用户",
      'phone': "-",
      'addr': "无",
      'psd_phone': '',
      'subject': subJect,
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "wxsmallpaycarts",
      'privatekey': privatekey,
      'del_source': 0,
      'add_source': 0,
      'message': that.selBosIsCongdian == 0 ? "自动售货机商品，无需发货" : "充电需求",
      'pin': pin,
      'ziti': 0,
      'isdraw': 0,
      'booktime': '不用配送',
      'guiid': that.guiId,
      'boxid': boxId,
      'mendianid': that.data.guiGoodsInfo.mendianid
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log("下单返回：", data);
        if (data.res === true) {
          if (price <= 0) {//金额为零的处理
            if (that.selBosIsCongdian != 0) {
              that.openchongdian(data.orderid, boxId);
            } else {
              that.setBoxEmpty(boxId);
            }
            that.hideBuyView();
          } else {
            //挂起微信支付请求
            var orderData = data.data;
            wx.requestPayment({
              'timeStamp': orderData.timeStamp,
              'nonceStr': orderData.nonceStr,
              'package': orderData.package,
              'signType': orderData.signType,
              'paySign': orderData.paySign,
              'success': function (res) {
                if (that.selBosIsCongdian != 0) {
                  that.openchongdian(data.orderid, boxId);
                } else {
                  that.setBoxEmpty(boxId);
                }
                that.hideBuyView();
              },
              'fail': function (res) {
                console.log(res);
                if (res.errMsg == 'requestPayment:fail cancel') {

                } else {
                  app.dialog('购买失败', 'loading');
                }
              }
            });
          }
        } else {
          app.dialog('购买失败', 'loading');
        }
      }
    });
  },

  //设置这个格子没有货物了
  setBoxEmpty: function (boxId) {

    wx.showLoading({
      title: 'loading...',
    });
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'setguibox' + that.data.token);
    var data = {
      'ac': "setguibox",
      'uid': that.data.cuid,
      'privatekey': privatekey,
      'guiid': that.guiId,
      'boxid': boxId,
      'setval': 0
    };
    console.log("设为已售：", data);

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log("设为已售返回：", data);
        if (data.res) {
          that.getGuiInfo();
        }
        wx.showModal({
          title: '温馨提示',
          content: '购买成功。稍后5秒左右，如舱门未弹开，可再次点击商品打开舱门',
          showCancel: false,
          confirmText: "确定",
        });
      }
    });
  },

  //打开舱门
  openGuiBox: function (boxId) {
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'openguibox' + that.data.token);
    var data = {
      'ac': "openguibox",
      'uid': that.data.cuid,
      'privatekey': privatekey,
      'guiid': that.guiId,
      'boxid': boxId
    };
    console.log("打开格子门", data);

    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log("打开格子门返回：", data);
        if (data.res) {
          wx.showToast({
            title: '请求发送成功',
          })
        } else {
          wx.showToast({
            title: '请求发送失败',
          })
        }
      }
    });
  },



  //充电指令
  openchongdian: function (orderid, boxId) {
    var that = this;
    that.selBosIsCongdian = 0;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'openchongdian' + that.data.token);
    var shichang = boxId == 6 ? (2 * 60) : (8 * 60);
    var data = {
      'ac': "openchongdian",
      'uid': that.data.cuid,
      'privatekey': privatekey,
      'guiid': that.guiId,
      'shichang': shichang,
      'order_id': orderid
    };
    console.log("充电指令", data);
    let cdtime = wx.getStorageSync('cdtime');
    if (!cdtime) {
      console.log("没有缓存");
      let curtime = (new Date().getTime()) / 1000;
      wx.setStorage({
        key: "cdtime",
        data: curtime
      });
      wx.setStorage({
        key: "orderid",
        data: orderid
      });
      wx.setStorage({
        key: "boxId",
        data: boxId
      });
    }
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        wx.hideLoading();
        var data = responseData.data;
        console.log("充电指令返回：", data);
        wx.showModal({
          title: '温馨提示',
          content: '充电功能已开启，如未能充电，十分钟内可多次点击电池图标重启充电功能',
          showCancel: false,
          confirmText: "确定",
        });
        if (data.res) {

        } else {

        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getAddress();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  goManageGuiPage: function () {
    var url = "/pages/manage_gui/manage_gui?guiid=" + this.guiId;
    wx.navigateTo({
      url: url
    })
  },
  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url
    })
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  //index 001  幻灯片数据
  loadSwiperImage: function () {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "indexslide",
      "uid": util.orgid,
      "block": 1,
      "tc": '',
    };
    util.api({
      data: params,
      success: function (responseData) {
        console.log("-- swiper image:", responseData);
        var result = responseData.data;
        if (result && result.length > 0) {
          //轮播图
          that.setData({
            swiperImgUrls: result
          });
        }
        wx.hideLoading();
      }
    });
  },

  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },

  recordId: '',
  recordScan: function () {
    // 记录扫码信息接口，post请求
    // 传入参数
    // ac = cdbaddsaoma
    // guiid - 机柜id
    // binduid - 商户uid
    // 返回
    // id - 扫码记录id
    var that = this;
    var data = {
      'ac': "cdbaddsaoma",
      'guiid': that.guiId
    };
    console.log("记录扫码：", data);
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        console.log("记录扫码结果：", responseData);
        that.recordId = responseData.data.id;
      }
    });
  },
  updateRecord: function () {
    // 更新扫码记录uid, post请求
    // 传入参数
    // ac = cdbupdatelogin
    // uid - 登陆用户uid
    // id - 扫码记录id
    var that = this;
    if (that.recordId) {
      var privatekey = utilMd5.hexMD5(that.data.cuid + 'cdbupdatelogin' + that.data.token);
      var data = {
        'ac': "cdbupdatelogin",
        'uid': that.data.cuid,
        'privatekey': privatekey,
        'id': that.recordId
      };
      console.log("更新扫码记录：", data);

      util.api({
        data: data,
        method: 'POST',
        success: function (responseData) {
          var data = responseData.data;
          console.log("更新扫码记录结果：", data);
        }
      });
    }
  },


})